<?php

namespace App\Repositories\WeChat;

/**
 * 微信小程序用户项目
 */


use GuzzleHttp\Client;

class WeChatUserXCXRepository
{


    private $config = [];
    private $client;

    public function __construct(
        Client $client
    )
    {
        $this->client = $client;
    }


    public function _config($config)
    {
        $this->config = $config;


        // 通过 bindRef 赋值对应的公众号配置，如果多公众号，也在这里判断配置
        $this->config['app_id'] = config('union.wechat.app_id');
        $this->config['app_secret'] = config('union.wechat.app_secret');
    }

    public function authorizeToken($code, $extend)
    {
        return $this->codeToSession($code);
    }

    /**
     * @api url https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

     * @param $code
     *
     * @return array|mixed
     */
    public function codeToSession($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $params = [
            'appid'      => $this->config['app_id'],
            'secret'     => $this->config['app_secret'],
            'js_code'       => $code,
            'grant_type' => 'authorization_code',
        ];

        try {
            $rs = $this->client->request('GET', $url, [
                'query' => $params
            ]);

            // 异常处理
            if (empty($rs) ||
                $rs->getStatusCode() != 200
            ) {

                return [];
            }

            $getContents = $rs->getBody()->getContents();
            $result = !empty($getContents) ? json_decode($getContents, true) : [];

            return $result;

        } catch (\Exception $exception) {

            return [];
        }
    }


    public function authorizeUser($openID, $accessToken)
    {

    }


}